package tut.thread.deadlock.ex2;

public class DeadLock {
	private String objId;
	
	public DeadLock(String id) {
		objId = id;
	}
	
	public synchronized void checkOther(DeadLock other) throws InterruptedException {
		print("entering action");
		Thread.sleep(500);
		print("Leaving action();");
	}
	
	public void print(String msg) {
		threadPrint("objectId=" + objId + " - " + msg);
	}
	
	public static void threadPrint(String msg) {
		String threadName = Thread.currentThread().getName();
		System.out.println(threadName + " : " + msg);
	}
	
	public static void main(String args[]) throws InterruptedException {
		final DeadLock obj1 = new DeadLock("obj1");
		final DeadLock obj2 = new DeadLock("obj2");
		
		Runnable runA = new Runnable() {
			
			@Override
			public void run() {
				try {
					obj1.checkOther(obj2);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
	
		Thread threadA = new Thread(runA, "threadA");
		threadA.start();
		Thread.sleep(200);
		
		Runnable runB = new Runnable() {
			
			@Override
			public void run() {
				try {
					obj2.checkOther(obj1);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		
		Thread threadB = new Thread(runB, "threadB");
		threadB.start();
		
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {}
		threadPrint("finished sleeping");
		threadPrint("about to interrupt() threadA");
		//threadA.interrupt();
		
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {}
		
		//threadB.interrupt();
		try {
			Thread.sleep(1000);
		} catch (Exception e) {	}

		threadPrint("did that break the deadlock ?");
	}
	
	

}
